package test.testsensor;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.model.LatLng;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class MainActivity extends Activity implements View.OnClickListener {
    LineChart lineChart;
    TextView tv;
    TextView tv_map;
    //sensor
    private SensorManager sensorManager;
    private Sensor accelerometer;

    private List<String> timeList = new ArrayList<>(); //存储x轴的时间

    int index = 0;



    // 定位相关
    private long saveLocationLastTime;
    private LocationClient mLocClient;
    public MyLocationListenner myListener = new MyLocationListenner();
    private MyApplication trackApp;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lineChart = findViewById(R.id.mainChart);
        tv = findViewById(R.id.tv_);
        tv_map = findViewById(R.id.tv_map);
        findViewById(R.id.btn_close).setOnClickListener(this);
        findViewById(R.id.btn_open).setOnClickListener(this);
        tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                index = 0;
            }
        });
        trackApp = (MyApplication) getApplicationContext();
        initLineView();
        initSensor();
        initMap();
    }

    @Override
    protected void onStart() {
        super.onStart();
        List<String> permissions = new ArrayList<>();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && isNeedRequestPermissions(permissions)) {
            requestPermissions(permissions.toArray(new String[permissions.size()]), 0);
        }
    }

    private boolean isNeedRequestPermissions(List<String> permissions) {
        // 定位精确位置
        addPermission(permissions, Manifest.permission.ACCESS_FINE_LOCATION);
        // 存储权限
        addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        // 读取手机状态
        addPermission(permissions, Manifest.permission.READ_PHONE_STATE);
        return permissions.size() > 0;
    }

    private void addPermission(List<String> permissionsList, String permission) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
                && checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
            permissionsList.add(permission);
        }
    }
    private void initMap() {
        // 定位初始化
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setIsNeedAddress(true);
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);
        //option.setNeedDeviceDirect(true);
        mLocClient.setLocOption(option);
        mLocClient.start();
    }

    private void initSensor() {
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        //register sensor
        if (accelerometer != null) {
            sensorManager.registerListener(mSensorEventListener,accelerometer, SensorManager.SENSOR_DELAY_FASTEST);//first sensor
        }
    }

    private SensorEventListener mSensorEventListener = new SensorEventListener() {
        @Override
        public void onSensorChanged(SensorEvent sensorEvent) {

            index++;
            tv.setText("累计上报："+index+"个数据");
            upDateAccelerometer(sensorEvent.values[0],sensorEvent.values[1],sensorEvent.values[2]);

        }
        @Override
        public void onAccuracyChanged(Sensor sensor, int i) {

        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_open:
                mLocClient.start();
                break;
            case R.id.btn_close:
                mLocClient.stop();
                break;
        }
    }


    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null ) {
                return;
            }
            tv_map.setText("Latitude:"+location.getLatitude()+",Longitude:"+location.getLongitude()+"\n"+
                    location.getAddrStr());
//
// getAddrStr
//            mCurrentLat = location.getLatitude();
//            mCurrentLon = location.getLongitude();
//            mCurrentAccracy = location.getRadius();
//            mCurrentSpeed = location.getSpeed();
//            mLocationTime = location.getTime();


        }

    }



    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        sensorManager.unregisterListener(mSensorEventListener);
    }

    private void initLineView() {
        //lineChart settings
        lineChart.getDescription().setText(" ");
        lineChart.getDescription().setEnabled(false);
        lineChart.setDragEnabled(true);
        lineChart.setTouchEnabled(true);
        lineChart.setScaleEnabled(false);
        lineChart.setDrawGridBackground(false);
        lineChart.setPinchZoom(false);
        lineChart.setNoDataTextColor(Color.GREEN);
        lineChart.setBackgroundColor(Color.WHITE);
        lineChart.setHighlightPerDragEnabled(false);
        lineChart.setDragDecelerationEnabled(true);


        lineChart.setNoDataText("没有数据");
        lineChart.setHighlightPerTapEnabled(true);
        lineChart.getAxisLeft().setDrawGridLines(true);
        lineChart.getXAxis().setDrawGridLines(false);
        lineChart.setDrawBorders(false);

        //initialize  LineData and add it to the chart
        LineData data = new LineData();
        data.setValueTextColor(Color.BLACK);
        lineChart.setData(data);


        //getting Legend object
        Legend legend = lineChart.getLegend();
        legend.setForm(Legend.LegendForm.LINE);
        legend.setTextColor(Color.BLACK);

        //drawing x ang y axis
        //Date groupCount = new Date();

        XAxis xAxis = lineChart.getXAxis();
        xAxis.setTextColor(Color.BLACK);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setAvoidFirstLastClipping(true);
        xAxis.setAxisLineWidth(3f);
        xAxis.setTextSize(12f);
        xAxis.setAxisLineColor(Color.BLACK);
        xAxis.setDrawGridLines(true);
        xAxis.setEnabled(true);
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return timeList.get((int) value % timeList.size());
            }
        });


        YAxis yAxisLeft = lineChart.getAxisLeft();
        yAxisLeft.setTextColor(Color.BLACK);
        yAxisLeft.setTextSize(12f);
        yAxisLeft.setAxisMaximum(5f);
        yAxisLeft.setAxisLineWidth(3f);//left宽度
        yAxisLeft.setAxisMaximum(150f);
        yAxisLeft.setDrawGridLines(true);
        yAxisLeft.setAxisLineColor(Color.BLACK);


        YAxis yAxisRight = lineChart.getAxisRight();
        yAxisRight.setTextColor(Color.BLACK);
        yAxisRight.setEnabled(false);
    }
    //add Entry to the line chart ( OnSensorChange )------------------------------------------------------
    private void upDateAccelerometer(float x, float y, float z) {
        LineData data = lineChart.getData();

        if (data != null) { // if plot already exist

            ILineDataSet setx = data.getDataSetByIndex(0);
            ILineDataSet sety = data.getDataSetByIndex(1);
            ILineDataSet setz = data.getDataSetByIndex(2);

            if (setx == null) {
                //create set and add
                setx = createLineDataSetx();
                data.addDataSet(setx);
            }
            if (sety == null) {
                //create set and add
                sety = createLineDataSety();
                data.addDataSet(sety);
            }
            if (setz == null) {
                //create set and add
                setz = createLineDataSetz();
                data.addDataSet(setz);
            }

            // adding new values (sensor data)
            data.addEntry(new Entry(setx.getEntryCount(), x), 0);
            data.addEntry(new Entry(sety.getEntryCount(), y), 1);
            data.addEntry(new Entry(setz.getEntryCount(), z), 2);
            timeList.add(TimeUtils.getNowTimeHH());
            lineChart.notifyDataSetChanged();
            lineChart.setVisibleXRangeMaximum(65);
            lineChart.moveViewToX(data.getEntryCount() - 65);
//            lineChart.getAxisLeft().setAxisMaximum(data.getYMax());
            lineChart.getAxisLeft().setAxisMaximum(45);
            lineChart.setMaxVisibleValueCount(120);
            lineChart.moveViewToX(data.getEntryCount()); // move to the next point
        }


    }

    //create data set
    private LineDataSet createLineDataSetx() {
        LineDataSet lineDataSetx = new LineDataSet(null, "x"); //draw data set
        //line settings here ....
        lineDataSetx.setFillAlpha(65);
        lineDataSetx.setAxisDependency(YAxis.AxisDependency.LEFT);
        lineDataSetx.setLineWidth(1f);
        //set1.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        lineDataSetx.setCubicIntensity(0.2f);
        lineDataSetx.setColor(Color.BLUE);
        lineDataSetx.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        lineDataSetx.setDrawCircles(false);
        lineDataSetx.setDrawValues(false);
        lineDataSetx.setHighlightEnabled(false);
//        lineDataSetx.setValueTextColor(Color.RED);


        //list of IDataSet if more than one
//        List<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
//        dataSets.add(lineDataSetx);
        return lineDataSetx;
    }
    //create data set
    private LineDataSet  createLineDataSety() {
        LineDataSet lineDataSety = new LineDataSet(null, "y"); //draw data set
        //line settings here ....
        lineDataSety.setFillAlpha(65);
        lineDataSety.setAxisDependency(YAxis.AxisDependency.LEFT);
        lineDataSety.setLineWidth(1f);
        //set1.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        lineDataSety.setCubicIntensity(0.2f);
        lineDataSety.setColor(Color.GREEN);
        lineDataSety.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        lineDataSety.setDrawCircles(false);
        lineDataSety.setDrawValues(false);
        lineDataSety.setHighlightEnabled(false);
//        lineDataSety.setValueTextColor(Color.RED);
        return lineDataSety;
    }
    //create data set
    private LineDataSet  createLineDataSetz() {
        LineDataSet lineDataSetz = new LineDataSet(null, "z"); //draw data set
        //line settings here ....
        lineDataSetz.setFillAlpha(65);
        lineDataSetz.setAxisDependency(YAxis.AxisDependency.LEFT);
        lineDataSetz.setLineWidth(1f);
        //set1.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        lineDataSetz.setCubicIntensity(0.2f);
        lineDataSetz.setColor(Color.RED);
        lineDataSetz.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        lineDataSetz.setDrawCircles(false);
        lineDataSetz.setDrawValues(false);
        lineDataSetz.setHighlightEnabled(false);
//        lineDataSetz.setValueTextColor(Color.RED);
        return lineDataSetz;
    }
}
